<script setup lang="ts">
import type { SelectBaseOption } from 'naive-ui/es/select/src/interface';

import type { BasicSelectProps } from '@/components/form/src/components/select/props';
import { usePageDataStore } from '@/store/modules/page-data';

defineOptions({
  name: 'BasicSelect',
});

const props = withDefaults(defineProps<BasicSelectProps>(), {
  consistentMenuWidth: true,
  disabled: false,
  labelField: 'label',
  multiple: false,
  options: [] as any,
  placeholder: '请选择',
  valueField: 'id',
  size: 'medium',
  defaultFirst: false,
});

const emits = defineEmits<{
  (e: 'update:value', value: any[] | string | number | null): void;
}>();

const localValue = ref();
const options = ref(props.options);

watchImmediate(() => props.value, value => {
  localValue.value = value;
});

/**
 * 获取共享数据
 *
 * 注意：监听会执行两次 第二次在表单项v-modal中
 */
watchImmediate(() => props.shareDataKey, key => {
  if (key) {
    options.value = usePageDataStore().get<Recordable[]>(key) ?? [];
    if (props.defaultFirst) {
      localValue.value = options.value[0]?.[props.valueField] as any;
    }
  }
});

function handleUpdateValue(
  value: any[] | string | number | null,
  _option: SelectBaseOption | null | SelectBaseOption[],
) {
  emits('update:value', value);
}
</script>

<template>
  <NSelect
    :consistent-menu-width="props.consistentMenuWidth"
    clearable
    :disabled="props.disabled"
    :label-field="props.labelField"
    :multiple="props.multiple"
    :options="options"
    :placeholder="props.placeholder"
    :value="localValue"
    :value-field="props.valueField"
    :size="props.size"
    filterable
    @update:value="handleUpdateValue"
  />
</template>

<style scoped lang="less">

</style>
